home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1998 November / Freeware November 1998.img / dist / fw_emacs.idb / usr / freeware / share / emacs / 19.34 / lisp / gomoku.el.z / gomoku.el
Lisp/Scheme  |  1998-10-27  |  44KB  |  1,183 lines

  1. ;;; gomoku.el --- Gomoku game between you and Emacs
  2.  
  3. ;; Copyright (C) 1988, 1994, 1996 Free Software Foundation, Inc.
  4.  
  5. ;; Author: Philippe Schnoebelen <phs@lifia.imag.fr>
  6. ;; Adapted-By: ESR, Daniel.Pfeiffer@Informatik.START.dbp.de
  7. ;; Keywords: games
  8.  
  9. ;; This file is part of GNU Emacs.
  10.  
  11. ;; GNU Emacs is free software; you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation; either version 2, or (at your option)
  14. ;; any later version.
  15.  
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19. ;; GNU General Public License for more details.
  20.  
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs; see the file COPYING.  If not, write to the
  23. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  24. ;; Boston, MA 02111-1307, USA.
  25.  
  26. ;;; Commentary:
  27.  
  28. ;; RULES:
  29. ;;
  30. ;; Gomoku is a game played between two players on a rectangular board.    Each
  31. ;; player, in turn, marks a free square of its choice. The winner is the first
  32. ;; one to mark five contiguous squares in any direction (horizontally,
  33. ;; vertically or diagonally).
  34. ;;
  35. ;; I have been told that, in "The TRUE Gomoku", some restrictions are made
  36. ;; about the squares where one may play, or else there is a known forced win
  37. ;; for the first player. This program has no such restriction, but it does not
  38. ;; know about the forced win, nor do I.     Furthermore, you probably do not know
  39. ;; it yourself :-).
  40.  
  41.  
  42. ;; There are two main places where you may want to customize the program: key
  43. ;; bindings and board display. These features are commented in the code. Go
  44. ;; and see.
  45.  
  46.  
  47. ;; HOW TO USE:
  48. ;;
  49. ;; The command "M-x gomoku" displays a
  50. ;; board, the size of which depends on the size of the current window. The
  51. ;; size of the board is easily modified by giving numeric arguments to the
  52. ;; gomoku command and/or by customizing the displaying parameters.
  53. ;;
  54. ;; Emacs plays when it is its turn. When it is your turn, just put the cursor
  55. ;; on the square where you want to play and hit RET, or X, or whatever key you
  56. ;; bind to the command gomoku-human-plays. When it is your turn, Emacs is
  57. ;; idle: you may switch buffers, read your mail, ... Just come back to the
  58. ;; *Gomoku* buffer and resume play.
  59.  
  60.  
  61. ;; ALGORITHM:
  62. ;;
  63. ;; The algorithm is briefly described in section "THE SCORE TABLE". Some
  64. ;; parameters may be modified if you want to change the style exhibited by the
  65. ;; program.
  66.  
  67. ;;; Code:
  68.  
  69. ;;;
  70. ;;; GOMOKU MODE AND KEYMAP.
  71. ;;;
  72. (defvar gomoku-mode-hook nil
  73.   "If non-nil, its value is called on entry to Gomoku mode.")
  74.  
  75. (defvar gomoku-mode-map nil
  76.   "Local keymap to use in Gomoku mode.")
  77.  
  78. (if gomoku-mode-map nil
  79.   (setq gomoku-mode-map (make-sparse-keymap))
  80.  
  81.   ;; Key bindings for cursor motion.
  82.   (define-key gomoku-mode-map "y" 'gomoku-move-nw)        ; y
  83.   (define-key gomoku-mode-map "u" 'gomoku-move-ne)        ; u
  84.   (define-key gomoku-mode-map "b" 'gomoku-move-sw)        ; b
  85.   (define-key gomoku-mode-map "n" 'gomoku-move-se)        ; n
  86.   (define-key gomoku-mode-map "h" 'backward-char)        ; h
  87.   (define-key gomoku-mode-map "l" 'forward-char)        ; l
  88.   (define-key gomoku-mode-map "j" 'gomoku-move-down)        ; j
  89.   (define-key gomoku-mode-map "k" 'gomoku-move-up)        ; k
  90.  
  91.   (define-key gomoku-mode-map [kp-7] 'gomoku-move-nw)
  92.   (define-key gomoku-mode-map [kp-9] 'gomoku-move-ne)
  93.   (define-key gomoku-mode-map [kp-1] 'gomoku-move-sw)
  94.   (define-key gomoku-mode-map [kp-3] 'gomoku-move-se)
  95.   (define-key gomoku-mode-map [kp-4] 'backward-char)
  96.   (define-key gomoku-mode-map [kp-6] 'forward-char)
  97.   (define-key gomoku-mode-map [kp-2] 'gomoku-move-down)
  98.   (define-key gomoku-mode-map [kp-8] 'gomoku-move-up)
  99.  
  100.   (define-key gomoku-mode-map "\C-n" 'gomoku-move-down)        ; C-n
  101.   (define-key gomoku-mode-map "\C-p" 'gomoku-move-up)        ; C-p
  102.  
  103.   ;; Key bindings for entering Human moves.
  104.   (define-key gomoku-mode-map "X" 'gomoku-human-plays)        ; X
  105.   (define-key gomoku-mode-map "x" 'gomoku-human-plays)        ; x
  106.   (define-key gomoku-mode-map " " 'gomoku-human-plays)        ; SPC
  107.   (define-key gomoku-mode-map "\C-m" 'gomoku-human-plays)    ; RET
  108.   (define-key gomoku-mode-map "\C-c\C-p" 'gomoku-human-plays)    ; C-c C-p
  109.   (define-key gomoku-mode-map "\C-c\C-b" 'gomoku-human-takes-back) ; C-c C-b
  110.   (define-key gomoku-mode-map "\C-c\C-r" 'gomoku-human-resigns)    ; C-c C-r
  111.   (define-key gomoku-mode-map "\C-c\C-e" 'gomoku-emacs-plays)    ; C-c C-e
  112.  
  113.   (define-key gomoku-mode-map [kp-enter] 'gomoku-human-plays)
  114.   (define-key gomoku-mode-map [insert] 'gomoku-human-plays)
  115.   (define-key gomoku-mode-map [down-mouse-1] 'gomoku-click)
  116.   (define-key gomoku-mode-map [drag-mouse-1] 'gomoku-click)
  117.   (define-key gomoku-mode-map [mouse-1] 'gomoku-click)
  118.   (define-key gomoku-mode-map [down-mouse-2] 'gomoku-click)
  119.   (define-key gomoku-mode-map [mouse-2] 'gomoku-mouse-play)
  120.   (define-key gomoku-mode-map [drag-mouse-2] 'gomoku-mouse-play)
  121.  
  122.   (substitute-key-definition 'previous-line 'gomoku-move-up
  123.                  gomoku-mode-map (current-global-map))
  124.   (substitute-key-definition 'next-line 'gomoku-move-down
  125.                  gomoku-mode-map (current-global-map))
  126.   (substitute-key-definition 'beginning-of-line 'gomoku-beginning-of-line
  127.                  gomoku-mode-map (current-global-map))
  128.   (substitute-key-definition 'end-of-line 'gomoku-end-of-line
  129.                  gomoku-mode-map (current-global-map))
  130.   (substitute-key-definition 'undo 'gomoku-human-takes-back
  131.                  gomoku-mode-map (current-global-map))
  132.   (substitute-key-definition 'advertised-undo 'gomoku-human-takes-back
  133.                  gomoku-mode-map (current-global-map)))
  134.  
  135. (defvar gomoku-emacs-won ()
  136.   "*For making font-lock use the winner's face for the line.")
  137.  
  138. (defvar gomoku-font-lock-O-face
  139.   (if window-system
  140.       (list (facemenu-get-face 'fg:red) 'bold))
  141.   "*Face to use for Emacs' O.")
  142.  
  143. (defvar gomoku-font-lock-X-face
  144.   (if window-system
  145.       (list (facemenu-get-face 'fg:green) 'bold))
  146.   "*Face to use for your X.")
  147.  
  148. (defvar gomoku-font-lock-keywords
  149.   '(("O" . gomoku-font-lock-O-face)
  150.     ("X" . gomoku-font-lock-X-face)
  151.     ("[-|/\\]" 0 (if gomoku-emacs-won
  152.              gomoku-font-lock-O-face
  153.            gomoku-font-lock-X-face)))
  154.   "*Font lock rules for Gomoku.")
  155.  
  156. (put 'gomoku-mode 'front-sticky
  157.      (put 'gomoku-mode 'rear-nonsticky '(intangible)))
  158. (put 'gomoku-mode 'intangible 1)
  159.  
  160. (defun gomoku-mode ()
  161.   "Major mode for playing Gomoku against Emacs.
  162. You and Emacs play in turn by marking a free square.  You mark it with X
  163. and Emacs marks it with O.  The winner is the first to get five contiguous
  164. marks horizontally, vertically or in diagonal.
  165.  
  166. You play by moving the cursor over the square you choose and hitting \\[gomoku-human-plays].
  167.  
  168. Other useful commands:
  169. \\{gomoku-mode-map}
  170. Entry to this mode calls the value of `gomoku-mode-hook' if that value
  171. is non-nil.  One interesting value is `turn-on-font-lock'."
  172.   (interactive)
  173.   (setq major-mode 'gomoku-mode
  174.     mode-name "Gomoku")
  175.   (gomoku-display-statistics)
  176.   (use-local-map gomoku-mode-map)
  177.   (make-local-variable 'font-lock-defaults)
  178.   (setq font-lock-defaults '(gomoku-font-lock-keywords t))
  179.   (toggle-read-only t)
  180.   (run-hooks 'gomoku-mode-hook))
  181.  
  182. ;;;
  183. ;;; THE BOARD.
  184. ;;;
  185.  
  186. ;; The board is a rectangular grid. We code empty squares with 0, X's with 1
  187. ;; and O's with 6. The rectangle is recorded in a one dimensional vector
  188. ;; containing padding squares (coded with -1). These squares allow us to
  189. ;; detect when we are trying to move out of the board.    We denote a square by
  190. ;; its (X,Y) coords, or by the INDEX corresponding to them in the vector.  The
  191. ;; leftmost topmost square has coords (1,1) and index gomoku-board-width + 2.
  192. ;; Similarly, vectors between squares may be given by two DX, DY coords or by
  193. ;; one DEPL (the difference between indexes).
  194.  
  195. (defvar gomoku-board-width nil
  196.   "Number of columns on the Gomoku board.")
  197.  
  198. (defvar gomoku-board-height nil
  199.   "Number of lines on the Gomoku board.")
  200.  
  201. (defvar gomoku-board nil
  202.   "Vector recording the actual state of the Gomoku board.")
  203.  
  204. (defvar gomoku-vector-length nil
  205.   "Length of gomoku-board vector.")
  206.  
  207. (defvar gomoku-draw-limit nil
  208.   ;; This is usually set to 70% of the number of squares.
  209.   "After how many moves will Emacs offer a draw?")
  210.  
  211.  
  212. (defun gomoku-xy-to-index (x y)
  213.   "Translate X, Y cartesian coords into the corresponding board index."
  214.   (+ (* y gomoku-board-width) x y))
  215.  
  216. (defun gomoku-index-to-x (index)
  217.   "Return corresponding x-coord of board INDEX."
  218.   (% index (1+ gomoku-board-width)))
  219.  
  220. (defun gomoku-index-to-y (index)
  221.   "Return corresponding y-coord of board INDEX."
  222.   (/ index (1+ gomoku-board-width)))
  223.  
  224. (defun gomoku-init-board ()
  225.   "Create the gomoku-board vector and fill it with initial values."
  226.   (setq gomoku-board (make-vector gomoku-vector-length 0))
  227.   ;; Every square is 0 (i.e. empty) except padding squares:
  228.   (let ((i 0) (ii (1- gomoku-vector-length)))
  229.     (while (<= i gomoku-board-width)    ; The squares in [0..width] and in
  230.       (aset gomoku-board i  -1)        ;    [length - width - 1..length - 1]
  231.       (aset gomoku-board ii -1)        ;    are padding squares.
  232.       (setq i  (1+ i)
  233.         ii (1- ii))))
  234.   (let ((i 0))
  235.     (while (< i gomoku-vector-length)
  236.       (aset gomoku-board i -1)        ; and also all k*(width+1)
  237.       (setq i (+ i gomoku-board-width 1)))))
  238.  
  239. ;;;
  240. ;;; THE SCORE TABLE.
  241. ;;;
  242.  
  243. ;; Every (free) square has a score associated to it, recorded in the
  244. ;; GOMOKU-SCORE-TABLE vector. The program always plays in the square having
  245. ;; the highest score.
  246.  
  247. (defvar gomoku-score-table nil
  248.   "Vector recording the actual score of the free squares.")
  249.  
  250.  
  251. ;; The key point point about the algorithm is that, rather than considering
  252. ;; the board as just a set of squares, we prefer to see it as a "space" of
  253. ;; internested 5-tuples of contiguous squares (called qtuples).
  254. ;;
  255. ;; The aim of the program is to fill one qtuple with its O's while preventing
  256. ;; you from filling another one with your X's. To that effect, it computes a
  257. ;; score for every qtuple, with better qtuples having better scores. Of
  258. ;; course, the score of a qtuple (taken in isolation) is just determined by
  259. ;; its contents as a set, i.e. not considering the order of its elements. The
  260. ;; highest score is given to the "OOOO" qtuples because playing in such a
  261. ;; qtuple is winning the game. Just after this comes the "XXXX" qtuple because
  262. ;; not playing in it is just loosing the game, and so on. Note that a
  263. ;; "polluted" qtuple, i.e. one containing at least one X and at least one O,
  264. ;; has score zero because there is no more any point in playing in it, from
  265. ;; both an attacking and a defending point of view.
  266. ;;
  267. ;; Given the score of every qtuple, the score of a given free square on the
  268. ;; board is just the sum of the scores of all the qtuples to which it belongs,
  269. ;; because playing in that square is playing in all its containing qtuples at
  270. ;; once. And it is that function which takes into account the internesting of
  271. ;; the qtuples.
  272. ;;
  273. ;; This algorithm is rather simple but anyway it gives a not so dumb level of
  274. ;; play. It easily extends to "n-dimensional Gomoku", where a win should not
  275. ;; be obtained with as few as 5 contiguous marks: 6 or 7 (depending on n !)
  276. ;; should be preferred.
  277.  
  278.  
  279. ;; Here are the scores of the nine "non-polluted" configurations.  Tuning
  280. ;; these values will change (hopefully improve) the strength of the program
  281. ;; and may change its style (rather aggressive here).
  282.  
  283. (defconst nil-score      7  "Score of an empty qtuple.")
  284. (defconst Xscore     15  "Score of a qtuple containing one X.")
  285. (defconst XXscore    400  "Score of a qtuple containing two X's.")
  286. (defconst XXXscore     1800  "Score of a qtuple containing three X's.")
  287. (defconst XXXXscore  100000  "Score of a qtuple containing four X's.")
  288. (defconst Oscore     35  "Score of a qtuple containing one O.")
  289. (defconst OOscore    800  "Score of a qtuple containing two O's.")
  290. (defconst OOOscore    15000  "Score of a qtuple containing three O's.")
  291. (defconst OOOOscore  800000  "Score of a qtuple containing four O's.")
  292.  
  293. ;; These values are not just random: if, given the following situation:
  294. ;;
  295. ;;              . . . . . . . O .
  296. ;;              . X X a . . . X .
  297. ;;              . . . X . . . X .
  298. ;;              . . . X . . . X .
  299. ;;              . . . . . . . b .
  300. ;;
  301. ;; you want Emacs to play in "a" and not in "b", then the parameters must
  302. ;; satisfy the inequality:
  303. ;;
  304. ;;           6 * XXscore > XXXscore + XXscore
  305. ;;
  306. ;; because "a" mainly belongs to six "XX" qtuples (the others are less
  307. ;; important) while "b" belongs to one "XXX" and one "XX" qtuples.  Other
  308. ;; conditions are required to obtain sensible moves, but the previous example
  309. ;; should illustrate the point. If you manage to improve on these values,
  310. ;; please send me a note. Thanks.
  311.  
  312.  
  313. ;; As we chose values 0, 1 and 6 to denote empty, X and O squares, the
  314. ;; contents of a qtuple are uniquely determined by the sum of its elements and
  315. ;; we just have to set up a translation table.
  316.  
  317. (defconst gomoku-score-trans-table
  318.   (vector nil-score Xscore XXscore XXXscore XXXXscore 0
  319.       Oscore    0       0       0        0          0
  320.       OOscore   0       0       0        0          0
  321.       OOOscore  0       0       0        0          0
  322.       OOOOscore 0       0       0        0          0
  323.       0)
  324.   "Vector associating qtuple contents to their score.")
  325.  
  326.  
  327. ;; If you do not modify drastically the previous constants, the only way for a
  328. ;; square to have a score higher than OOOOscore is to belong to a "OOOO"
  329. ;; qtuple, thus to be a winning move. Similarly, the only way for a square to
  330. ;; have a score between XXXXscore and OOOOscore is to belong to a "XXXX"
  331. ;; qtuple. We may use these considerations to detect when a given move is
  332. ;; winning or loosing.
  333.  
  334. (defconst gomoku-winning-threshold OOOOscore
  335.   "Threshold score beyond which an Emacs move is winning.")
  336.  
  337. (defconst gomoku-loosing-threshold XXXXscore
  338.   "Threshold score beyond which a human move is winning.")
  339.  
  340.  
  341. (defun gomoku-strongest-square ()
  342.   "Compute index of free square with highest score, or nil if none."
  343.   ;; We just have to loop other all squares. However there are two problems:
  344.   ;; 1/ The SCORE-TABLE only gives correct scores to free squares. To speed
  345.   ;;    up future searches, we set the score of padding or occupied squares
  346.   ;;    to -1 whenever we meet them.
  347.   ;; 2/ We want to choose randomly between equally good moves.
  348.   (let ((score-max 0)
  349.     (count       0)            ; Number of equally good moves
  350.     (square       (gomoku-xy-to-index 1 1)) ; First square
  351.     (end       (gomoku-xy-to-index gomoku-board-width gomoku-board-height))
  352.     best-square score)
  353.     (while (<= square end)
  354.       (cond
  355.        ;; If score is lower (i.e. most of the time), skip to next:
  356.        ((< (aref gomoku-score-table square) score-max))
  357.        ;; If score is better, beware of non free squares:
  358.        ((> (setq score (aref gomoku-score-table square)) score-max)
  359.     (if (zerop (aref gomoku-board square)) ; is it free ?
  360.         (setq count 1               ; yes: take it !
  361.           best-square square
  362.           score-max   score)
  363.         (aset gomoku-score-table square -1))) ; no: kill it !
  364.        ;; If score is equally good, choose randomly. But first check freeness:
  365.        ((not (zerop (aref gomoku-board square)))
  366.     (aset gomoku-score-table square -1))
  367.        ((zerop (random (setq count (1+ count))))
  368.     (setq best-square square
  369.           score-max      score)))
  370.       (setq square (1+ square)))    ; try next square
  371.     best-square))
  372.  
  373. ;;;
  374. ;;; INITIALIZING THE SCORE TABLE.
  375. ;;;
  376.  
  377. ;; At initialization the board is empty so that every qtuple amounts for
  378. ;; nil-score. Therefore, the score of any square is nil-score times the number
  379. ;; of qtuples that pass through it. This number is 3 in a corner and 20 if you
  380. ;; are sufficiently far from the sides. As computing the number is time
  381. ;; consuming, we initialize every square with 20*nil-score and then only
  382. ;; consider squares at less than 5 squares from one side. We speed this up by
  383. ;; taking symmetry into account.
  384. ;; Also, as it is likely that successive games will be played on a board with
  385. ;; same size, it is a good idea to save the initial SCORE-TABLE configuration.
  386.  
  387. (defvar gomoku-saved-score-table nil
  388.   "Recorded initial value of previous score table.")
  389.  
  390. (defvar gomoku-saved-board-width nil
  391.   "Recorded value of previous board width.")
  392.  
  393. (defvar gomoku-saved-board-height nil
  394.   "Recorded value of previous board height.")
  395.  
  396.  
  397. (defun gomoku-init-score-table ()
  398.   "Create the score table vector and fill it with initial values."
  399.   (if (and gomoku-saved-score-table    ; Has it been stored last time ?
  400.        (= gomoku-board-width  gomoku-saved-board-width)
  401.        (= gomoku-board-height gomoku-saved-board-height))
  402.       (setq gomoku-score-table (copy-sequence gomoku-saved-score-table))
  403.       ;; No, compute it:
  404.       (setq gomoku-score-table
  405.         (make-vector gomoku-vector-length (* 20 nil-score)))
  406.       (let (i j maxi maxj maxi2 maxj2)
  407.     (setq maxi  (/ (1+ gomoku-board-width) 2)
  408.           maxj  (/ (1+ gomoku-board-height) 2)
  409.           maxi2 (min 4 maxi)
  410.           maxj2 (min 4 maxj))
  411.     ;; We took symmetry into account and could use it more if the board
  412.     ;; would have been square and not rectangular !
  413.     ;; In our case we deal with all (i,j) in the set [1..maxi2]*[1..maxj] U
  414.     ;; [maxi2+1..maxi]*[1..maxj2]. Maxi2 and maxj2 are used because the
  415.     ;; board may well be less than 8 by 8 !
  416.     (setq i 1)
  417.     (while (<= i maxi2)
  418.       (setq j 1)
  419.       (while (<= j maxj)
  420.         (gomoku-init-square-score i j)
  421.         (setq j (1+ j)))
  422.       (setq i (1+ i)))
  423.     (while (<= i maxi)
  424.       (setq j 1)
  425.       (while (<= j maxj2)
  426.         (gomoku-init-square-score i j)
  427.         (setq j (1+ j)))
  428.       (setq i (1+ i))))
  429.       (setq gomoku-saved-score-table  (copy-sequence gomoku-score-table)
  430.         gomoku-saved-board-width  gomoku-board-width
  431.         gomoku-saved-board-height gomoku-board-height)))
  432.  
  433. (defun gomoku-nb-qtuples (i j)
  434.   "Return the number of qtuples containing square I,J."
  435.   ;; This function is complicated because we have to deal
  436.   ;; with ugly cases like 3 by 6 boards, but it works.
  437.   ;; If you have a simpler (and correct) solution, send it to me. Thanks !
  438.   (let ((left  (min 4 (1- i)))
  439.     (right (min 4 (- gomoku-board-width i)))
  440.     (up    (min 4 (1- j)))
  441.     (down  (min 4 (- gomoku-board-height j))))
  442.     (+ -12
  443.        (min (max (+ left right) 3) 8)
  444.        (min (max (+ up down) 3) 8)
  445.        (min (max (+ (min left up) (min right down)) 3) 8)
  446.        (min (max (+ (min right up) (min left down)) 3) 8))))
  447.  
  448. (defun gomoku-init-square-score (i j)
  449.   "Give initial score to square I,J and to its mirror images."
  450.   (let ((ii (1+ (- gomoku-board-width i)))
  451.     (jj (1+ (- gomoku-board-height j)))
  452.     (sc (* (gomoku-nb-qtuples i j) (aref gomoku-score-trans-table 0))))
  453.     (aset gomoku-score-table (gomoku-xy-to-index i  j)    sc)
  454.     (aset gomoku-score-table (gomoku-xy-to-index ii j)    sc)
  455.     (aset gomoku-score-table (gomoku-xy-to-index i  jj) sc)
  456.     (aset gomoku-score-table (gomoku-xy-to-index ii jj) sc)))
  457.  
  458. ;;;
  459. ;;; MAINTAINING THE SCORE TABLE.
  460. ;;;
  461.  
  462. ;; We do not provide functions for computing the SCORE-TABLE given the
  463. ;; contents of the BOARD. This would involve heavy nested loops, with time
  464. ;; proportional to the size of the board. It is better to update the
  465. ;; SCORE-TABLE after each move. Updating needs not modify more than 36
  466. ;; squares: it is done in constant time.
  467.  
  468. (defun gomoku-update-score-table (square dval)
  469.   "Update score table after SQUARE received a DVAL increment."
  470.   ;; The board has already been updated when this function is called.
  471.   ;; Updating scores is done by looking for qtuples boundaries in all four
  472.   ;; directions and then calling update-score-in-direction.
  473.   ;; Finally all squares received the right increment, and then are up to
  474.   ;; date, except possibly for SQUARE itself if we are taking a move back for
  475.   ;; its score had been set to -1 at the time.
  476.   (let* ((x    (gomoku-index-to-x square))
  477.      (y    (gomoku-index-to-y square))
  478.      (imin (max -4 (- 1 x)))
  479.      (jmin (max -4 (- 1 y)))
  480.      (imax (min 0 (- gomoku-board-width x 4)))
  481.      (jmax (min 0 (- gomoku-board-height y 4))))
  482.     (gomoku-update-score-in-direction imin imax
  483.                       square 1 0 dval)
  484.     (gomoku-update-score-in-direction jmin jmax
  485.                       square 0 1 dval)
  486.     (gomoku-update-score-in-direction (max imin jmin) (min imax jmax)
  487.                       square 1 1 dval)
  488.     (gomoku-update-score-in-direction (max (- 1 y) -4
  489.                        (- x gomoku-board-width))
  490.                       (min 0 (- x 5)
  491.                        (- gomoku-board-height y 4))
  492.                       square -1 1 dval)))
  493.  
  494. (defun gomoku-update-score-in-direction (left right square dx dy dval)
  495.   "Update scores for all squares in the qtuples starting between the LEFTth
  496. square and the RIGHTth after SQUARE, along the DX, DY direction, considering
  497. that DVAL has been added on SQUARE."
  498.   ;; We always have LEFT <= 0, RIGHT <= 0 and DEPL > 0 but we may very well
  499.   ;; have LEFT > RIGHT, indicating that no qtuple contains SQUARE along that
  500.   ;; DX,DY direction.
  501.   (cond
  502.    ((> left right))            ; Quit
  503.    (t                    ; Else ..
  504.     (let (depl square0 square1 square2 count delta)
  505.       (setq depl    (gomoku-xy-to-index dx dy)
  506.         square0 (+ square (* left depl))
  507.         square1 (+ square (* right depl))
  508.         square2 (+ square0 (* 4 depl)))
  509.       ;; Compute the contents of the first qtuple:
  510.       (setq square square0
  511.         count  0)
  512.       (while (<= square square2)
  513.     (setq count  (+ count (aref gomoku-board square))
  514.           square (+ square depl)))
  515.       (while (<= square0 square1)
  516.     ;; Update the squares of the qtuple beginning in SQUARE0 and ending
  517.     ;; in SQUARE2.
  518.     (setq delta (- (aref gomoku-score-trans-table count)
  519.                (aref gomoku-score-trans-table (- count dval))))
  520.     (cond ((not (zerop delta))    ; or else nothing to update
  521.            (setq square square0)
  522.            (while (<= square square2)
  523.          (if (zerop (aref gomoku-board square)) ; only for free squares
  524.              (aset gomoku-score-table square
  525.                (+ (aref gomoku-score-table square) delta)))
  526.          (setq square (+ square depl)))))
  527.     ;; Then shift the qtuple one square along DEPL, this only requires
  528.     ;; modifying SQUARE0 and SQUARE2.
  529.     (setq square2 (+ square2 depl)
  530.           count   (+ count (- (aref gomoku-board square0))
  531.              (aref gomoku-board square2))
  532.           square0 (+ square0 depl)))))))
  533.  
  534. ;;;
  535. ;;; GAME CONTROL.
  536. ;;;
  537.  
  538. ;; Several variables are used to monitor a game, including a GAME-HISTORY (the
  539. ;; list of all (SQUARE . PREVSCORE) played) that allows to take moves back
  540. ;; (anti-updating the score table) and to compute the table from scratch in
  541. ;; case of an interruption.
  542.  
  543. (defvar gomoku-game-in-progress nil
  544.   "Non-nil if a game is in progress.")
  545.  
  546. (defvar gomoku-game-history nil
  547.   "A record of all moves that have been played during current game.")
  548.  
  549. (defvar gomoku-number-of-moves nil
  550.   "Number of moves already played in current game.")
  551.  
  552. (defvar gomoku-number-of-human-moves nil
  553.   "Number of moves already played by human in current game.")
  554.  
  555. (defvar gomoku-emacs-played-first nil
  556.   "Non-nil if Emacs played first.")
  557.  
  558. (defvar gomoku-human-took-back nil
  559.   "Non-nil if Human took back a move during the game.")
  560.  
  561. (defvar gomoku-human-refused-draw nil
  562.   "Non-nil if Human refused Emacs offer of a draw.")
  563.  
  564. (defvar gomoku-emacs-is-computing nil
  565.   ;; This is used to detect interruptions. Hopefully, it should not be needed.
  566.   "Non-nil if Emacs is in the middle of a computation.")
  567.  
  568.  
  569. (defun gomoku-start-game (n m)
  570.   "Initialize a new game on an N by M board."
  571.   (setq gomoku-emacs-is-computing t)    ; Raise flag
  572.   (setq gomoku-game-in-progress t)
  573.   (setq gomoku-board-width   n
  574.     gomoku-board-height  m
  575.     gomoku-vector-length (1+ (* (+ m 2) (1+ n)))
  576.     gomoku-draw-limit    (/ (* 7 n m) 10))
  577.   (setq gomoku-emacs-won         nil
  578.     gomoku-game-history         nil
  579.     gomoku-number-of-moves         0
  580.     gomoku-number-of-human-moves 0
  581.     gomoku-emacs-played-first    nil
  582.     gomoku-human-took-back         nil
  583.     gomoku-human-refused-draw    nil)
  584.   (gomoku-init-display n m)        ; Display first: the rest takes time
  585.   (gomoku-init-score-table)        ; INIT-BOARD requires that the score
  586.   (gomoku-init-board)            ;   table be already created.
  587.   (setq gomoku-emacs-is-computing nil))
  588.  
  589. (defun gomoku-play-move (square val &optional dont-update-score)
  590.   "Go to SQUARE, play VAL and update everything."
  591.   (setq gomoku-emacs-is-computing t)    ; Raise flag
  592.   (cond ((= 1 val)            ; a Human move
  593.      (setq gomoku-number-of-human-moves (1+ gomoku-number-of-human-moves)))
  594.     ((zerop gomoku-number-of-moves)    ; an Emacs move. Is it first ?
  595.      (setq gomoku-emacs-played-first t)))
  596.   (setq gomoku-game-history
  597.     (cons (cons square (aref gomoku-score-table square))
  598.           gomoku-game-history)
  599.     gomoku-number-of-moves (1+ gomoku-number-of-moves))
  600.   (gomoku-plot-square square val)
  601.   (aset gomoku-board square val)    ; *BEFORE* UPDATE-SCORE !
  602.   (if dont-update-score nil
  603.       (gomoku-update-score-table square val) ; previous val was 0: dval = val
  604.       (aset gomoku-score-table square -1))
  605.   (setq gomoku-emacs-is-computing nil))
  606.  
  607. (defun gomoku-take-back ()
  608.   "Take back last move and update everything."
  609.   (setq gomoku-emacs-is-computing t)
  610.   (let* ((last-move (car gomoku-game-history))
  611.      (square (car last-move))
  612.      (oldval (aref gomoku-board square)))
  613.     (if (= 1 oldval)
  614.     (setq gomoku-number-of-human-moves (1- gomoku-number-of-human-moves)))
  615.     (setq gomoku-game-history     (cdr gomoku-game-history)
  616.       gomoku-number-of-moves (1- gomoku-number-of-moves))
  617.     (gomoku-plot-square square 0)
  618.     (aset gomoku-board square 0)    ; *BEFORE* UPDATE-SCORE !
  619.     (gomoku-update-score-table square (- oldval))
  620.     (aset gomoku-score-table square (cdr last-move)))
  621.   (setq gomoku-emacs-is-computing nil))
  622.  
  623. ;;;
  624. ;;; SESSION CONTROL.
  625. ;;;
  626.  
  627. (defvar gomoku-number-of-emacs-wins 0
  628.   "Number of games Emacs won in this session.")
  629.  
  630. (defvar gomoku-number-of-human-wins 0
  631.   "Number of games you won in this session.")
  632.  
  633. (defvar gomoku-number-of-draws 0
  634.   "Number of games already drawn in this session.")
  635.  
  636.  
  637. (defun gomoku-terminate-game (result)
  638.   "Terminate the current game with RESULT."
  639.   (message
  640.    (cond
  641.     ((eq result 'emacs-won)
  642.      (setq gomoku-number-of-emacs-wins (1+ gomoku-number-of-emacs-wins))
  643.      (cond ((< gomoku-number-of-moves 20)
  644.         "This was a REALLY QUICK win.")
  645.        (gomoku-human-refused-draw
  646.         "I won... Too bad you refused my offer of a draw !")
  647.        (gomoku-human-took-back
  648.         "I won... Taking moves back will not help you !")
  649.        ((not gomoku-emacs-played-first)
  650.         "I won... Playing first did not help you much !")
  651.        ((and (zerop gomoku-number-of-human-wins)
  652.          (zerop gomoku-number-of-draws)
  653.          (> gomoku-number-of-emacs-wins 1))
  654.         "I'm becoming tired of winning...")
  655.        ("I won.")))
  656.     ((eq result 'human-won)
  657.      (setq gomoku-number-of-human-wins (1+ gomoku-number-of-human-wins))
  658.      (concat "OK, you won this one."
  659.          (cond
  660.           (gomoku-human-took-back
  661.            "  I, for one, never take my moves back...")
  662.           (gomoku-emacs-played-first
  663.            ".. so what ?")
  664.           ("  Now, let me play first just once."))))
  665.     ((eq result 'human-resigned)
  666.      (setq gomoku-number-of-emacs-wins (1+ gomoku-number-of-emacs-wins))
  667.      "So you resign.  That's just one more win for me.")
  668.     ((eq result 'nobody-won)
  669.      (setq gomoku-number-of-draws (1+ gomoku-number-of-draws))
  670.      (concat "This is a draw.  "
  671.          (cond
  672.           (gomoku-human-took-back
  673.            "I, for one, never take my moves back...")
  674.           (gomoku-emacs-played-first
  675.            "Just chance, I guess.")
  676.           ("Now, let me play first just once."))))
  677.     ((eq result 'draw-agreed)
  678.      (setq gomoku-number-of-draws (1+ gomoku-number-of-draws))
  679.      (concat "Draw agreed.  "
  680.          (cond
  681.           (gomoku-human-took-back
  682.            "I, for one, never take my moves back...")
  683.           (gomoku-emacs-played-first
  684.            "You were lucky.")
  685.           ("Now, let me play first just once."))))
  686.     ((eq result 'crash-game)
  687.      "Sorry, I have been interrupted and cannot resume that game...")))
  688.   (gomoku-display-statistics)
  689.   ;;(ding)
  690.   (setq gomoku-game-in-progress nil))
  691.  
  692. (defun gomoku-crash-game ()
  693.   "What to do when Emacs detects it has been interrupted."
  694.   (setq gomoku-emacs-is-computing nil)
  695.   (gomoku-terminate-game 'crash-game)
  696.   (sit-for 4)                ; Let's see the message
  697.   (gomoku-prompt-for-other-game))
  698.  
  699. ;;;
  700. ;;; INTERACTIVE COMMANDS.
  701. ;;;
  702.  
  703. ;;;###autoload
  704. (defun gomoku (&optional n m)
  705.   "Start a Gomoku game between you and Emacs.
  706. If a game is in progress, this command allow you to resume it.
  707. If optional arguments N and M are given, an N by M board is used.
  708. If prefix arg is given for N, M is prompted for.
  709.  
  710. You and Emacs play in turn by marking a free square.  You mark it with X
  711. and Emacs marks it with O. The winner is the first to get five contiguous
  712. marks horizontally, vertically or in diagonal.
  713.  
  714. You play by moving the cursor over the square you choose and hitting
  715. \\<gomoku-mode-map>\\[gomoku-human-plays].
  716. Use \\[describe-mode] for more info."
  717.   (interactive (if current-prefix-arg
  718.            (list (prefix-numeric-value current-prefix-arg)
  719.              (eval (read-minibuffer "Height: ")))))
  720.   (gomoku-switch-to-window)
  721.   (cond
  722.    (gomoku-emacs-is-computing
  723.     (gomoku-crash-game))
  724.    ((or (not gomoku-game-in-progress)
  725.     (<= gomoku-number-of-moves 2))
  726.     (let ((max-width (gomoku-max-width))
  727.       (max-height (gomoku-max-height)))
  728.       (or n (setq n max-width))
  729.       (or m (setq m max-height))
  730.       (cond ((< n 1)
  731.          (error "I need at least 1 column"))
  732.         ((< m 1)
  733.          (error "I need at least 1 row"))
  734.         ((> n max-width)
  735.          (error "I cannot display %d columns in that window" n)))
  736.       (if (and (> m max-height)
  737.            (not (eq m gomoku-saved-board-height))
  738.            ;; Use EQ because SAVED-BOARD-HEIGHT may be nil
  739.            (not (y-or-n-p (format "Do you really want %d rows " m))))
  740.       (setq m max-height)))
  741.     (message "One moment, please...")
  742.     (gomoku-start-game n m)
  743.     (if (y-or-n-p "Do you allow me to play first ")
  744.     (gomoku-emacs-plays)
  745.     (gomoku-prompt-for-move)))
  746.    ((y-or-n-p "Shall we continue our game ")
  747.     (gomoku-prompt-for-move))
  748.    (t
  749.     (gomoku-human-resigns))))
  750.  
  751. (defun gomoku-emacs-plays ()
  752.   "Compute Emacs next move and play it."
  753.   (interactive)
  754.   (gomoku-switch-to-window)
  755.   (cond
  756.    (gomoku-emacs-is-computing
  757.     (gomoku-crash-game))
  758.    ((not gomoku-game-in-progress)
  759.     (gomoku-prompt-for-other-game))
  760.    (t
  761.     (message "Let me think...")
  762.     (let (square score)
  763.       (setq square (gomoku-strongest-square))
  764.       (cond ((null square)
  765.          (gomoku-terminate-game 'nobody-won))
  766.         (t
  767.          (setq score (aref gomoku-score-table square))
  768.          (gomoku-play-move square 6)
  769.          (cond ((>= score gomoku-winning-threshold)
  770.             (setq gomoku-emacs-won t) ; for font-lock
  771.             (gomoku-find-filled-qtuple square 6)
  772.             (gomoku-terminate-game 'emacs-won))
  773.            ((zerop score)
  774.             (gomoku-terminate-game 'nobody-won))
  775.            ((and (> gomoku-number-of-moves gomoku-draw-limit)
  776.              (not gomoku-human-refused-draw)
  777.              (gomoku-offer-a-draw))
  778.             (gomoku-terminate-game 'draw-agreed))
  779.            (t
  780.             (gomoku-prompt-for-move)))))))))
  781.  
  782. ;; For small square dimensions this is approximate, since though measured in
  783. ;; pixels, event's (X . Y) is a character's top-left corner.
  784. (defun gomoku-click (click)
  785.   "Position at the square where you click."
  786.   (interactive "e")
  787.   (and (windowp (posn-window (setq click (event-end click))))
  788.        (numberp (posn-point click))
  789.        (select-window (posn-window click))
  790.        (setq click (posn-col-row click))
  791.        (gomoku-goto-xy
  792.     (min (max (/ (+ (- (car click)
  793.                gomoku-x-offset
  794.                1)
  795.             (window-hscroll)
  796.             gomoku-square-width
  797.             (% gomoku-square-width 2)
  798.             (/ gomoku-square-width 2))
  799.              gomoku-square-width)
  800.           1)
  801.          gomoku-board-width)
  802.     (min (max (/ (+ (- (cdr click)
  803.                gomoku-y-offset
  804.                1)
  805.             (let ((inhibit-point-motion-hooks t))
  806.               (count-lines 1 (window-start)))
  807.             gomoku-square-height
  808.             (% gomoku-square-height 2)
  809.             (/ gomoku-square-height 2))
  810.              gomoku-square-height)
  811.           1)
  812.          gomoku-board-height))))
  813.   
  814. (defun gomoku-mouse-play (click)
  815.   "Play at the square where you click."
  816.   (interactive "e")
  817.   (if (gomoku-click click)
  818.       (gomoku-human-plays)))
  819.  
  820. (defun gomoku-human-plays ()
  821.   "Signal to the Gomoku program that you have played.
  822. You must have put the cursor on the square where you want to play.
  823. If the game is finished, this command requests for another game."
  824.   (interactive)
  825.   (gomoku-switch-to-window)
  826.   (cond
  827.    (gomoku-emacs-is-computing
  828.     (gomoku-crash-game))
  829.    ((not gomoku-game-in-progress)
  830.     (gomoku-prompt-for-other-game))
  831.    (t
  832.     (let (square score)
  833.       (setq square (gomoku-point-square))
  834.       (cond ((null square)
  835.          (error "Your point is not on a square. Retry !"))
  836.         ((not (zerop (aref gomoku-board square)))
  837.          (error "Your point is not on a free square. Retry !"))
  838.         (t
  839.          (setq score (aref gomoku-score-table square))
  840.          (gomoku-play-move square 1)
  841.          (cond ((and (>= score gomoku-loosing-threshold)
  842.              ;; Just testing SCORE > THRESHOLD is not enough for
  843.              ;; detecting wins, it just gives an indication that
  844.              ;; we confirm with GOMOKU-FIND-FILLED-QTUPLE.
  845.              (gomoku-find-filled-qtuple square 1))
  846.             (gomoku-terminate-game 'human-won))
  847.            (t
  848.             (gomoku-emacs-plays)))))))))
  849.  
  850. (defun gomoku-human-takes-back ()
  851.   "Signal to the Gomoku program that you wish to take back your last move."
  852.   (interactive)
  853.   (gomoku-switch-to-window)
  854.   (cond
  855.    (gomoku-emacs-is-computing
  856.     (gomoku-crash-game))
  857.    ((not gomoku-game-in-progress)
  858.     (message "Too late for taking back...")
  859.     (sit-for 4)
  860.     (gomoku-prompt-for-other-game))
  861.    ((zerop gomoku-number-of-human-moves)
  862.     (message "You have not played yet... Your move ?"))
  863.    (t
  864.     (message "One moment, please...")
  865.     ;; It is possible for the user to let Emacs play several consecutive
  866.     ;; moves, so that the best way to know when to stop taking back moves is
  867.     ;; to count the number of human moves:
  868.     (setq gomoku-human-took-back t)
  869.     (let ((number gomoku-number-of-human-moves))
  870.       (while (= number gomoku-number-of-human-moves)
  871.     (gomoku-take-back)))
  872.     (gomoku-prompt-for-move))))
  873.  
  874. (defun gomoku-human-resigns ()
  875.   "Signal to the Gomoku program that you may want to resign."
  876.   (interactive)
  877.   (gomoku-switch-to-window)
  878.   (cond
  879.    (gomoku-emacs-is-computing
  880.     (gomoku-crash-game))
  881.    ((not gomoku-game-in-progress)
  882.     (message "There is no game in progress"))
  883.    ((y-or-n-p "You mean, you resign ")
  884.     (gomoku-terminate-game 'human-resigned))
  885.    ((y-or-n-p "You mean, we continue ")
  886.     (gomoku-prompt-for-move))
  887.    (t
  888.     (gomoku-terminate-game 'human-resigned)))) ; OK. Accept it
  889.  
  890. ;;;
  891. ;;; PROMPTING THE HUMAN PLAYER.
  892. ;;;
  893.  
  894. (defun gomoku-prompt-for-move ()
  895.   "Display a message asking for Human's move."
  896.   (message (if (zerop gomoku-number-of-human-moves)
  897.            "Your move ? (move to a free square and hit X, RET ...)"
  898.            "Your move ?"))
  899.   ;; This may seem silly, but if one omits the following line (or a similar
  900.   ;; one), the cursor may very well go to some place where POINT is not.
  901.   (save-excursion (set-buffer (other-buffer))))
  902.  
  903. (defun gomoku-prompt-for-other-game ()
  904.   "Ask for another game, and start it."
  905.   (if (y-or-n-p "Another game ")
  906.       (gomoku gomoku-board-width gomoku-board-height)
  907.     (message "Chicken !")))
  908.  
  909. (defun gomoku-offer-a-draw ()
  910.   "Offer a draw and return T if Human accepted it."
  911.   (or (y-or-n-p "I offer you a draw. Do you accept it ")
  912.       (not (setq gomoku-human-refused-draw t))))
  913.  
  914. ;;;
  915. ;;; DISPLAYING THE BOARD.
  916. ;;;
  917.  
  918. ;; You may change these values if you have a small screen or if the squares
  919. ;; look rectangular, but spacings SHOULD be at least 2 (MUST BE at least 1).
  920.  
  921. (defconst gomoku-square-width 4
  922.   "*Horizontal spacing between squares on the Gomoku board.")
  923.  
  924. (defconst gomoku-square-height 2
  925.   "*Vertical spacing between squares on the Gomoku board.")
  926.  
  927. (defconst gomoku-x-offset 3
  928.   "*Number of columns between the Gomoku board and the side of the window.")
  929.  
  930. (defconst gomoku-y-offset 1
  931.   "*Number of lines between the Gomoku board and the top of the window.")
  932.  
  933.  
  934. (defun gomoku-max-width ()
  935.   "Largest possible board width for the current window."
  936.   (1+ (/ (- (window-width (selected-window))
  937.         gomoku-x-offset gomoku-x-offset 1)
  938.      gomoku-square-width)))
  939.  
  940. (defun gomoku-max-height ()
  941.   "Largest possible board height for the current window."
  942.   (1+ (/ (- (window-height (selected-window))
  943.         gomoku-y-offset gomoku-y-offset 2)
  944.      ;; 2 instead of 1 because WINDOW-HEIGHT includes the mode line !
  945.      gomoku-square-height)))
  946.  
  947. (defun gomoku-point-y ()
  948.   "Return the board row where point is."
  949.   (let ((inhibit-point-motion-hooks t))
  950.     (1+ (/ (- (count-lines 1 (point)) gomoku-y-offset (if (bolp) 0 1))
  951.        gomoku-square-height))))
  952.  
  953. (defun gomoku-point-square ()
  954.   "Return the index of the square point is on."
  955.   (let ((inhibit-point-motion-hooks t))
  956.     (gomoku-xy-to-index (1+ (/ (- (current-column) gomoku-x-offset)
  957.                    gomoku-square-width))
  958.             (gomoku-point-y))))
  959.  
  960. (defun gomoku-goto-square (index)
  961.   "Move point to square number INDEX."
  962.   (gomoku-goto-xy (gomoku-index-to-x index) (gomoku-index-to-y index)))
  963.  
  964. (defun gomoku-goto-xy (x y)
  965.   "Move point to square at X, Y coords."
  966.   (let ((inhibit-point-motion-hooks t))
  967.     (goto-line (+ 1 gomoku-y-offset (* gomoku-square-height (1- y)))))
  968.   (move-to-column (+ gomoku-x-offset (* gomoku-square-width (1- x)))))
  969.  
  970. (defun gomoku-plot-square (square value)
  971.   "Draw 'X', 'O' or '.' on SQUARE depending on VALUE, leave point there."
  972.   (or (= value 1)
  973.       (gomoku-goto-square square))
  974.   (let ((inhibit-read-only t)
  975.     (inhibit-point-motion-hooks t))
  976.     (insert-and-inherit (cond ((= value 1) ?X)
  977.                   ((= value 6) ?O)
  978.                   (?.)))
  979.     (and window-system
  980.      (zerop value)
  981.      (put-text-property (1- (point)) (point) 'mouse-face 'highlight))
  982.     (delete-char 1)
  983.     (backward-char 1))
  984.   (sit-for 0))    ; Display NOW
  985.  
  986. (defun gomoku-init-display (n m)
  987.   "Display an N by M Gomoku board."
  988.   (buffer-disable-undo (current-buffer))
  989.   (let ((inhibit-read-only t)
  990.     (point 1) opoint
  991.     (intangible t)
  992.     (i m) j x)
  993.     ;; Try to minimize number of chars (because of text properties)
  994.     (setq tab-width
  995.       (if (zerop (% gomoku-x-offset gomoku-square-width))
  996.           gomoku-square-width
  997.         (max (/ (+ (% gomoku-x-offset gomoku-square-width)
  998.                gomoku-square-width 1) 2) 2)))
  999.     (erase-buffer)
  1000.     (newline gomoku-y-offset)
  1001.     (while (progn
  1002.          (setq j n
  1003.            x (- gomoku-x-offset gomoku-square-width))
  1004.          (while (>= (setq j (1- j)) 0)
  1005.            (insert-char ?\t (/ (- (setq x (+ x gomoku-square-width))
  1006.                       (current-column))
  1007.                    tab-width))
  1008.            (insert-char ?  (- x (current-column)))
  1009.            (if (setq intangible (not intangible))
  1010.            (put-text-property point (point) 'intangible 2))
  1011.            (and (zerop j)
  1012.             (= i (- m 2))
  1013.             (progn
  1014.               (while (>= i 3)
  1015.             (append-to-buffer (current-buffer) opoint (point))
  1016.             (setq i (- i 2)))
  1017.               (goto-char (point-max))))
  1018.            (setq point (point))
  1019.            (insert ?.)
  1020.            (if window-system
  1021.            (put-text-property point (point)
  1022.                       'mouse-face 'highlight)))
  1023.          (> (setq i (1- i)) 0))
  1024.       (if (= i (1- m))
  1025.       (setq opoint point))
  1026.       (insert-char ?\n gomoku-square-height))
  1027.     (or (eq (char-after 1) ?.)
  1028.     (put-text-property 1 2 'point-entered
  1029.                (lambda (x x) (if (bobp) (forward-char)))))
  1030.     (or intangible
  1031.     (put-text-property point (point) 'intangible 2))
  1032.     (put-text-property point (point) 'point-entered
  1033.                (lambda (x x) (if (eobp) (backward-char))))
  1034.     (put-text-property (point-min) (point) 'category 'gomoku-mode))
  1035.   (gomoku-goto-xy (/ (1+ n) 2) (/ (1+ m) 2)) ; center of the board
  1036.   (sit-for 0))                ; Display NOW
  1037.  
  1038. (defun gomoku-display-statistics ()
  1039.   "Obnoxiously display some statistics about previous games in mode line."
  1040.   ;; We store this string in the mode-line-process local variable.
  1041.   ;; This is certainly not the cleanest way out ...
  1042.   (setq mode-line-process
  1043.     (format ": Won %d, lost %d%s"
  1044.         gomoku-number-of-human-wins
  1045.         gomoku-number-of-emacs-wins
  1046.         (if (zerop gomoku-number-of-draws)
  1047.             ""
  1048.           (format ", drew %d" gomoku-number-of-draws))))
  1049.   (force-mode-line-update))
  1050.  
  1051. (defun gomoku-switch-to-window ()
  1052.   "Find or create the Gomoku buffer, and display it."
  1053.   (interactive)
  1054.   (let ((buff (get-buffer "*Gomoku*")))
  1055.     (if buff                ; Buffer exists:
  1056.     (switch-to-buffer buff)        ;   no problem.
  1057.       (if gomoku-game-in-progress
  1058.       (gomoku-crash-game))        ;   buffer has been killed or something
  1059.       (switch-to-buffer "*Gomoku*")    ; Anyway, start anew.
  1060.       (gomoku-mode))))
  1061.  
  1062. ;;;
  1063. ;;; CROSSING WINNING QTUPLES.
  1064. ;;;
  1065.  
  1066. ;; When someone succeeds in filling a qtuple, we draw a line over the five
  1067. ;; corresponding squares. One problem is that the program does not know which
  1068. ;; squares ! It only knows the square where the last move has been played and
  1069. ;; who won. The solution is to scan the board along all four directions.
  1070.  
  1071. (defun gomoku-find-filled-qtuple (square value)
  1072.   "Return T if SQUARE belongs to a qtuple filled with VALUEs."
  1073.   (or (gomoku-check-filled-qtuple square value 1 0)
  1074.       (gomoku-check-filled-qtuple square value 0 1)
  1075.       (gomoku-check-filled-qtuple square value 1 1)
  1076.       (gomoku-check-filled-qtuple square value -1 1)))
  1077.  
  1078. (defun gomoku-check-filled-qtuple (square value dx dy)
  1079.   "Return T if SQUARE belongs to a qtuple filled  with VALUEs along DX, DY."
  1080.   (let ((a 0) (b 0)
  1081.     (left square) (right square)
  1082.     (depl (gomoku-xy-to-index dx dy)))
  1083.     (while (and (> a -4)        ; stretch tuple left
  1084.         (= value (aref gomoku-board (setq left (- left depl)))))
  1085.       (setq a (1- a)))
  1086.     (while (and (< b (+ a 4))        ; stretch tuple right
  1087.         (= value (aref gomoku-board (setq right (+ right depl)))))
  1088.       (setq b (1+ b)))
  1089.     (cond ((= b (+ a 4))        ; tuple length = 5 ?
  1090.        (gomoku-cross-qtuple (+ square (* a depl)) (+ square (* b depl))
  1091.                 dx dy)
  1092.        t))))
  1093.  
  1094. (defun gomoku-cross-qtuple (square1 square2 dx dy)
  1095.   "Cross every square between SQUARE1 and SQUARE2 in the DX, DY direction."
  1096.   (save-excursion            ; Not moving point from last square
  1097.     (let ((depl (gomoku-xy-to-index dx dy))
  1098.       (inhibit-read-only t)
  1099.       (inhibit-point-motion-hooks t))
  1100.       ;; WARNING: this function assumes DEPL > 0 and SQUARE2 > SQUARE1
  1101.       (while (/= square1 square2)
  1102.     (gomoku-goto-square square1)
  1103.     (setq square1 (+ square1 depl))
  1104.     (cond
  1105.       ((= dy 0)            ; Horizontal
  1106.        (forward-char 1)
  1107.        (insert-char ?- (1- gomoku-square-width) t)
  1108.        (delete-region (point) (progn
  1109.                     (skip-chars-forward " \t")
  1110.                     (point))))
  1111.       ((= dx 0)            ; Vertical
  1112.        (let ((n 1)
  1113.          (column (current-column)))
  1114.          (while (< n gomoku-square-height)
  1115.            (setq n (1+ n))
  1116.            (forward-line 1)
  1117.            (indent-to column)
  1118.            (insert-and-inherit ?|))))
  1119.       ((= dx -1)            ; 1st Diagonal
  1120.        (indent-to (prog1 (- (current-column) (/ gomoku-square-width 2))
  1121.             (forward-line (/ gomoku-square-height 2))))
  1122.        (insert-and-inherit ?/))
  1123.       (t                ; 2nd Diagonal
  1124.        (indent-to (prog1 (+ (current-column) (/ gomoku-square-width 2))
  1125.             (forward-line (/ gomoku-square-height 2))))
  1126.        (insert-and-inherit ?\\))))))
  1127.   (sit-for 0))                ; Display NOW
  1128.  
  1129. ;;;
  1130. ;;; CURSOR MOTION.
  1131. ;;;
  1132. ;; previous-line and next-line don't work right with intangible newlines
  1133. (defun gomoku-move-down ()
  1134.   "Move point down one row on the Gomoku board."
  1135.   (interactive)
  1136.   (if (< (gomoku-point-y) gomoku-board-height)
  1137.       (next-line gomoku-square-height)))
  1138.  
  1139. (defun gomoku-move-up ()
  1140.   "Move point up one row on the Gomoku board."
  1141.   (interactive)
  1142.   (if (> (gomoku-point-y) 1)
  1143.       (previous-line gomoku-square-height)))
  1144.  
  1145. (defun gomoku-move-ne ()
  1146.   "Move point North East on the Gomoku board."
  1147.   (interactive)
  1148.   (gomoku-move-up)
  1149.   (forward-char))
  1150.  
  1151. (defun gomoku-move-se ()
  1152.   "Move point South East on the Gomoku board."
  1153.   (interactive)
  1154.   (gomoku-move-down)
  1155.   (forward-char))
  1156.  
  1157. (defun gomoku-move-nw ()
  1158.   "Move point North West on the Gomoku board."
  1159.   (interactive)
  1160.   (gomoku-move-up)
  1161.   (backward-char))
  1162.  
  1163. (defun gomoku-move-sw ()
  1164.   "Move point South West on the Gomoku board."
  1165.   (interactive)
  1166.   (gomoku-move-down)
  1167.   (backward-char))
  1168.  
  1169. (defun gomoku-beginning-of-line ()
  1170.   "Move point to first square on the Gomoku board row."
  1171.   (interactive)
  1172.   (move-to-column gomoku-x-offset))
  1173.  
  1174. (defun gomoku-end-of-line ()
  1175.   "Move point to last square on the Gomoku board row."
  1176.   (interactive)
  1177.   (move-to-column (+ gomoku-x-offset
  1178.              (* gomoku-square-width (1- gomoku-board-width)))))
  1179.  
  1180. (provide 'gomoku)
  1181.  
  1182. ;;; gomoku.el ends here
  1183.